package cn.hicard.auth.web.ctrl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hicard.auth.entity.MgSource;
import cn.hicard.auth.service.SourceService;
import cn.hicard.auth.web.AuthFilter;
import cn.hicard.auth.web.Node;
import cn.hicard.auth.web.util.WebUI;

@Controller
@RequestMapping("/auth/source")
public class SourceCtrl {
	
	@Autowired
	private SourceService sourceService;
	
	/**
	 * 初始化加载页面，加载顶级树形结构
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public String list(@RequestParam(required=false) Integer pk, ModelMap map) throws Exception{		
		// 从根开始，查找导航类型控件组成的树，如果未传入或传入其它值则修正为资源视图，否则就是菜单视图
		if(pk == null || pk == AuthFilter.ROOT_SOURCE_PK){
			pk = AuthFilter.ROOT_SOURCE_PK;
		}else if(pk == AuthFilter.ROOT_MENU_PK){
			pk = AuthFilter.ROOT_MENU_PK;
		}else{
			pk = AuthFilter.ROOT_SOURCE_PK;
		}
		Node tree = sourceService.findNodeByType(pk, Node.TYPE_NAVI);
		String html = WebUI.buildNaviTree(tree, "'leafClickHandler(this)'","'labelClickHandler(this, {0})'");
		map.put("tree", html);		
		return "/auth/source";
	}
		
	/**
	 * 用于处理ajax请求提交的表单：保存
	 * @param sourceid
	 * @param sourcename
	 * @param sourcetype
	 * @throws Exception 
	 */
	@RequestMapping(value="/save.do", method=RequestMethod.POST)
	public String save(@RequestParam("sourceid")String sourceid,
			@RequestParam("sourcename")String sourcename,
			@RequestParam("sourcetype")String sourcetype,
			@RequestParam("parent")int parent) throws Exception{
		MgSource source = new MgSource();
		source.setControlid(sourceid);
		source.setSourcename(sourcename);
		source.setSourcetype(sourcetype);
		source.setParentid(parent);	
		sourceService.save(source);
		// 操作完成，更新选中的节点与相应列表
		return "forward:/auth/source/navilist.do";
	}
	
	/**
	 * 用于处理ajax请求提交的表单：更新
	 * @param pk
	 * @param sourceid
	 * @param sourcename
	 * @throws Exception
	 */
	@RequestMapping(value="/update.do", method=RequestMethod.POST)
	public String update(@RequestParam("pk")int pk,
			@RequestParam("sourceid")String sourceid,
			@RequestParam("sourcename")String sourcename) throws Exception{
		MgSource source = sourceService.getOne(pk);
		source.setControlid(sourceid);
		source.setSourcename(sourcename);
		sourceService.update(source);
		// 操作完成，更新选中的节点与相应列表
		
		return "forward:/auth/source/navilist.do";
	}
	
	/**
	 * 用于处理ajax请求：删除
	 * @param pk
	 * @throws Exception
	 */
	@RequestMapping(value="/delete.do", method=RequestMethod.POST)
	public String delete(@RequestParam("pk")int pk) throws Exception{
		sourceService.delete(pk);
		// 操作完成，更新选中的节点与相应列表
		
		return "forward:/auth/source/navilist.do";
	}
	
	/**
	 * 生成导航类型资源的树装HTML
	 * @param startPk
	 * @return
	 * @throws Exception
	 */
	public String createNaviTree(int startPk) throws Exception{
		Node tree = sourceService.findNodeByType(0, Node.TYPE_NAVI);
		return WebUI.buildNaviTree(tree, "'leafClickHandler(this)'","'labelClickHandler(this, {0})'");
	}
	
	@RequestMapping(value="/navilist.do")
	@ResponseBody
	public String findNaviAndChildrenByParent(@RequestParam("parent")int pk) throws Exception{
		// 从指定树形节点开始的HTML
		Node naviTree = sourceService.findNodeByType(pk, Node.TYPE_NAVI);
		String tree = WebUI.buildNaviTree(naviTree, "'leafClickHandler(this)'","'labelClickHandler(this, {0})'");		
		// 列表所的JSON对象
		String list = findChildrenByParent(pk);
		
		StringBuilder json = new StringBuilder();
		json.append("{tree:\"");
		json.append(tree);
		json.append("\",list:");
		json.append(list);
		json.append("}");
		return json.toString();
	}
	
	/**
	 * 用于处理ajax请求，查询指定节点下的子节点，反回子集合的json字符串<br/>
	 * 为了代码的可移植性，这里就不用第三方包来生成JSON了，反正对象也比较简单
	 * @param pk
	 * @param map
	 * @throws Exception
	 */
	@RequestMapping("/children.do")
	@ResponseBody
	public String findChildrenByParent(@RequestParam("parent")int pk) throws Exception{
		StringBuilder sourceJson = new StringBuilder();
		List<MgSource> sources = sourceService.findByParent(pk);
		sourceJson.append("[");
		for (int i = 0; i < sources.size(); i++) {
			MgSource source = sources.get(i);
			sourceJson.append("{pkSource:'");
			sourceJson.append(source.getPkSource());
			sourceJson.append("',controlid:'");
			sourceJson.append(source.getControlid());
			sourceJson.append("',sourcename:'");
			sourceJson.append(source.getSourcename());
			sourceJson.append("',sourcetype:'");
			sourceJson.append(source.getSourcetype());
			sourceJson.append("',parentid:'");
			sourceJson.append(source.getParentid());
			sourceJson.append("'}");
			if(i < sources.size()-1){
				sourceJson.append(",");	
			}
		}
		sourceJson.append("]");
		return sourceJson.toString();
	}
	

}
